package com.attilax.orm;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.attilax.dataService.DataService;
import com.attilax.sql.DupliRecord;
import com.attilax.sql.SqlService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Inject;

public class AtiOrm extends DataService {
	
	

	private String table;
	public String update="update";
	private String op;
	public Map m=Maps.newLinkedHashMap();

public AtiOrm( ) {
	//this.m=m;

}

	public AtiOrm(Map m) {
		this.m=m;
	
	}

	public AtiOrm setTable(String tb) {
		this.table=tb;
		this.m.put("$table", tb);
		return this;
	}

	public void setOp(String opString) {
		this.op=opString;
		this.m.put("$op", opString);
	}
	  @Inject
	protected
	 SqlService sqlSrv;
	private String tabletype;
	public Object exe(Map m) {
		processTable(m);
		processOp(m);
	//	super.exe(m);
		String sql = d2sSrv.dsl2sql(m);
		System.out.println("dsl2sql:sqlis:"+sql);
		if (StringUtils.isEmpty(sql))
			throw new RuntimeException(
					" cant convert sql str rzt is null or empty:"+d2sSrv);
		return sqlSrv.exe(sql);
		
	}

	public AtiOrm tabletype(String tabletype) {
		this.tabletype=tabletype;
		return this;
	}
	public boolean existRzt;
	public Map querySingleRow;
	public List<Map> queryRows=Lists.newLinkedList();
	public AtiOrm exist(String s) {
	    List<Map>  li=sqlSrv.executeQuery(s); 
	    if(li.size()>=0)
	    querySingleRow=li.get(0);
	    existRzt=(li.size()>=1);
	    return this;
		
	}
	
	
	public AtiOrm query(String s) {
	    List<Map>  li=sqlSrv.executeQuery(s); 
	//    if(li.size()>=0)
	    this.queryRows=li;
	  //  existRzt=(li.size()>=1);
     return this;
		
	}

	/**
	 * with uniq check
	attilax    2016年4月21日  下午9:31:19
	 * @param s
	 * @return
	 */
	public AtiOrm querySingleRow(String s) {
		   List<Map>  li=sqlSrv.executeQuery(s); 
		     if(li.size()>0)
		    	 this.querySingleRow=li.get(0);
		     if(li.size()>1)
		    	 throw new DupliRecord(" sql:"+s);
		return this;
	}
	
	public AtiOrm querySingleRow_NoUniqCheck(String s) {
		   List<Map>  li=sqlSrv.executeQuery(s); 
		     if(li.size()>0)
		    	 this.querySingleRow=li.get(0);
		 //    if(li.size()>1)
		    //	 throw new DupliRecord(" sql:"+s);
		return this;
	}


	public AtiOrm exist(String col, String val) {
		  String sql = "select * from "+this.table+" where "+col+"='"+val+"'";
		  System.out.println(sql);
		List<Map>  li=sqlSrv.executeQuery(sql); 
		    if(li.size()>0)
		    querySingleRow=li.get(0);
		    existRzt=(li.size()>=1);
		    return this;
	}
	
	public AtiOrm existUniq(String col, String val) {
		  String sql = "select * from "+this.table+" where "+col+"='"+val+"'";
		  System.out.println(sql);
		List<Map>  li=sqlSrv.executeQuery(sql); 
		  if(li.size()>1)
		    	 throw new DupliRecord(" sql:"+sql);
		    if(li.size()>0)
		    	querySingleRow=li.get(0);
		    existRzt=(li.size()>=1);
		    return this;
	}
	
	
	
	

}
